package com.css.zfzx.sjcj.modules.hddcB7_VolcanicSampleResultTable.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcB7_VolcanicSampleResultTable.repository.HddcB7VolcanicsampleresulttableNativeRepository;
import com.css.zfzx.sjcj.modules.hddcB7_VolcanicSampleResultTable.repository.HddcB7VolcanicsampleresulttableRepository;
import com.css.zfzx.sjcj.modules.hddcB7_VolcanicSampleResultTable.repository.entity.HddcB7VolcanicsampleresulttableEntity;
import com.css.zfzx.sjcj.modules.hddcB7_VolcanicSampleResultTable.service.HddcB7VolcanicsampleresulttableService;
import com.css.zfzx.sjcj.modules.hddcB7_VolcanicSampleResultTable.viewobjects.HddcB7VolcanicsampleresulttableQueryParams;
import com.css.zfzx.sjcj.modules.hddcB7_VolcanicSampleResultTable.viewobjects.HddcB7VolcanicsampleresulttableVO;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author zhangcong
 * @date 2020-11-26
 */
@Service
public class HddcB7VolcanicsampleresulttableServiceImpl implements HddcB7VolcanicsampleresulttableService {

	@Autowired
    private HddcB7VolcanicsampleresulttableRepository hddcB7VolcanicsampleresulttableRepository;
    @Autowired
    private HddcB7VolcanicsampleresulttableNativeRepository hddcB7VolcanicsampleresulttableNativeRepository;

    @Override
    public JSONObject queryHddcB7Volcanicsampleresulttables(HddcB7VolcanicsampleresulttableQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcB7VolcanicsampleresulttableEntity> hddcB7VolcanicsampleresulttablePage = this.hddcB7VolcanicsampleresulttableNativeRepository.queryHddcB7Volcanicsampleresulttables(queryParams, curPage, pageSize, sort, order);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcB7VolcanicsampleresulttablePage);
        return jsonObject;
    }


    @Override
    public HddcB7VolcanicsampleresulttableEntity getHddcB7Volcanicsampleresulttable(String id) {
        HddcB7VolcanicsampleresulttableEntity hddcB7Volcanicsampleresulttable = this.hddcB7VolcanicsampleresulttableRepository.findById(id).orElse(null);
         return hddcB7Volcanicsampleresulttable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcB7VolcanicsampleresulttableEntity saveHddcB7Volcanicsampleresulttable(HddcB7VolcanicsampleresulttableEntity hddcB7Volcanicsampleresulttable) {
        String uuid = UUIDGenerator.getUUID();
        hddcB7Volcanicsampleresulttable.setUuid(uuid);
        hddcB7Volcanicsampleresulttable.setCreateUser(PlatformSessionUtils.getUserId());
        hddcB7Volcanicsampleresulttable.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcB7Volcanicsampleresulttable.setIsValid("1");
        this.hddcB7VolcanicsampleresulttableRepository.save(hddcB7Volcanicsampleresulttable);
        return hddcB7Volcanicsampleresulttable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcB7VolcanicsampleresulttableEntity updateHddcB7Volcanicsampleresulttable(HddcB7VolcanicsampleresulttableEntity hddcB7Volcanicsampleresulttable) {
        UpdateUtil.copyNullProperties(hddcB7VolcanicsampleresulttableRepository.findByUuidAndIsValid(hddcB7Volcanicsampleresulttable.getUuid(), "1"), hddcB7Volcanicsampleresulttable);
        hddcB7Volcanicsampleresulttable.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcB7Volcanicsampleresulttable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcB7VolcanicsampleresulttableRepository.save(hddcB7Volcanicsampleresulttable);
        return hddcB7Volcanicsampleresulttable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcB7Volcanicsampleresulttables(List<String> ids) {
        List<HddcB7VolcanicsampleresulttableEntity> hddcB7VolcanicsampleresulttableList = this.hddcB7VolcanicsampleresulttableRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcB7VolcanicsampleresulttableList) && hddcB7VolcanicsampleresulttableList.size() > 0) {
            for(HddcB7VolcanicsampleresulttableEntity hddcB7Volcanicsampleresulttable : hddcB7VolcanicsampleresulttableList) {
                hddcB7Volcanicsampleresulttable.setIsValid("0");
                hddcB7Volcanicsampleresulttable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcB7Volcanicsampleresulttable.setUpdateTime(new Date());
                this.hddcB7VolcanicsampleresulttableRepository.save(hddcB7Volcanicsampleresulttable);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public void exportFile(HddcB7VolcanicsampleresulttableQueryParams queryParams, HttpServletResponse response) {
        List<HddcB7VolcanicsampleresulttableEntity> yhDisasterEntities = hddcB7VolcanicsampleresulttableNativeRepository.exportYhDisasters(queryParams);
        List<HddcB7VolcanicsampleresulttableVO> list=new ArrayList<>();
        for (HddcB7VolcanicsampleresulttableEntity entity:yhDisasterEntities) {
            HddcB7VolcanicsampleresulttableVO yhDisasterVO=new HddcB7VolcanicsampleresulttableVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list, "火山调查采样测试结果表", "火山调查采样测试结果表", HddcB7VolcanicsampleresulttableVO.class, "火山调查采样测试结果表.xls", response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcB7VolcanicsampleresulttableVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcB7VolcanicsampleresulttableVO.class, params);
            List<HddcB7VolcanicsampleresulttableVO> list = result.getList();
            // Excel条数据
            int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size() ));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcB7VolcanicsampleresulttableVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcB7VolcanicsampleresulttableVO yhDisasterVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + yhDisasterVO.getRowNum() + "行" + yhDisasterVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }
    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList( List<HddcB7VolcanicsampleresulttableVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcB7VolcanicsampleresulttableEntity yhDisasterEntity = new HddcB7VolcanicsampleresulttableEntity();
            HddcB7VolcanicsampleresulttableVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcB7Volcanicsampleresulttable(yhDisasterEntity);
        }
    }

}
